// 标签页数据
import { defineStore } from "pinia";

import router from "../../router";

interface tabType {
  title: string;
  path: string;
  type: string;
}

interface TabState {
  tabArray: tabType[];
  currentPath: string;
}

export const useTabStore = defineStore("tab", {
  // 初始化状态
  state: (): TabState => ({
    tabArray: [{ title: "主页", path: "./", type: "success" }],
    currentPath: "",
  }),
  // 计算属性
  getters: {},
  // 操作方法
  actions: {
    // 增加
    increment(title: string, path: string) {
      // 是否为新的tab
      let result = this.tabArray.every(function (item) {
        return item.title !== title;
      });

      if (result) {
        // 将新的tab改为success
        this.tabArray.push({ title: title, path: path, type: "success" });
        if (this.tabArray.length > 5) {
          this.tabArray.shift();
        }
      } else {
        // 如果不是新的tab 就将当前选中的旧的tab改为success
        this.tabArray.map((i) => {
          if (i.title == title) {
            i.type = "success";
          }
        });
      }
      // 将不是当前的页面 type修改为primary
      this.tabArray.map((i) => {
        if (i.title !== title) {
          i.type = "primary";
        }
      });
    },
    // 删除 close
    tabClose(val: any) {
      this.tabArray = this.tabArray.filter((item) => item.title !== val.title);
      if (this.tabArray.length == 0) {
        this.tabArray.push({ title: "主页", path: "./", type: "success" });
        router.replace("./");
      } else {
        router.replace(this.tabArray[this.tabArray.length - 1].path);
      }
    },
    // 点击 click
    tabClick(val: any) {
      console.log("tabClick", val);

      router.replace(val.path);
      this.tabArray.map((i) => {
        if (i.path !== val.path) {
          i.type = "primary";
        } else {
          i.type = "success";
        }
      });
    },
  },
});
